# flask 迁移数据
from flask_migrate import Migrate
from app import create_app, celery_app
from ext import db
from app.models.users import User, Article, ChangeLogs, RevokedTokenModel
from app.models.todo import Todo
import click
from flask import jsonify, make_response

app = create_app(config_name="DEVELOPMENT")

# celery
# 关键点，往celery推入flask信息，使得celery能使用flask上下文
app.app_context().push()

db.init_app(app)

# 传入2个对象一个是flask的app对象，一个是SQLAlchemy
migrate = Migrate(app, db)


@app.shell_context_processor
def make_shell_context():
    return dict(db=db, Users=User, Todo=Todo, Article=Article, ChangeLogs=ChangeLogs,
                RevokedTokenModel=RevokedTokenModel)


@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
    """Init databases."""
    if drop:
        click.confirm(
            'This operation will delete the database, do you want to continue?',
            abort=True)
        db.drop_all()
        click.echo('Drop tables.')
    db.create_all()
    click.echo('Initialized database.')


@app.cli.command()
@click.argument('test_names', nargs=-1)
def test(test_names):
    """Run the unit tests."""
    import unittest
    if test_names:
        tests = unittest.TestLoader().loadTestsFromNames(test_names)
    else:
        tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)


# 改善404 错误处理程序
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)


# 改善400 错误处理程序
@app.errorhandler(400)
def not_found(error):
    return make_response(jsonify({'error': 'Bad Request'}), 400)
